﻿namespace JobButenko.Controllers
{
    using System.Web.Mvc;

    using JobButenko.Models;
    using JobButenko.Models.BusinessLogicLayer;

    public class VacancyController : Controller
    {
        // GET: /Vacancy/
        private readonly DataManager dataManager;

        public VacancyController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }

        public ActionResult Search()
        {
            GetData();
            return View();
        }

        [HttpPost]
        public ActionResult Search(Vacancy vacancy)
        {
            ViewData.Model = this.dataManager.Vacancy.SearchVacancy(vacancy);
            return View("ViewSearchVacancy");
        }

        public JsonResult GetPost(int profFieldId)
        {
            var result = new JsonResult
                             {
                                 JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                                 Data = PostModel.GetPositions(profFieldId)
                             };
            return result;
        }

        public ActionResult CreateVacancy()
        {
            GetData();
            return View();
        }

        [HttpPost]
        public ActionResult CreateVacancy(Vacancy vacancy)
        {
            this.dataManager.Vacancy.AddVacancy(vacancy);
            return RedirectToAction("ViewVacancy", "Vacancy");
        }

        public ActionResult ViewVacancy()
        {
            ViewData.Model = this.dataManager.Vacancy.GetVacancyFromUser(User.Identity.Name);
            return View();
        }

        private void GetData(int? profField = 0, int? post = 0, int? salary = 0)
        {
            ViewData["ProfField"] = new SelectList(
                this.dataManager.ProfessionalField.GetProfField(), "ProfFieldId", "ProfFieldName", profField);
            ViewData["Post"] = new SelectList(this.dataManager.Post.GetPost(), "PostId", "PostName", post);
            ViewData["Salary"] = new SelectList(this.dataManager.Salary.GetSalary(), "SalaryId", "SalaryVol", salary);
        }

        public ActionResult EditVacancy(int id)
        {
            Vacancy vacancy = this.dataManager.Vacancy.GetVacancyFromId(id);
            ViewData.Model = vacancy;
            this.GetData(vacancy.ProfFieldId, vacancy.PostId, vacancy.SalaryId);
            return View();
        }

        [HttpPost]
        public ActionResult EditVacancy(int id, Vacancy vacancy)
        {
            this.dataManager.Vacancy.UpdateVacancy(id, vacancy);
            return RedirectToAction("ViewVacancy");
        }

        public ActionResult DeleteVacancy(int id)
        {
            this.dataManager.Vacancy.DeleteVacancy(id);
            return RedirectToAction("ViewVacancy");
        }
    }
}